<template>
    <Layout>
        <Form ref="form1" :model="form1" :label-width="120">
            <Row v-show="!switchFlag" class="query-form" >
                <Col span="8">
                    <FormItem label="企业名称：" prop="belongOrgId">
                        <cascaderDom class="query-form-el" ref="carOrg"
                                     @setOrgInfo="setQueryOrgId" @setOrgName="setQueryOrgName" :orgTree="true"></cascaderDom>
                    </FormItem>
                </Col>
                <Col span="8">
                    <FormItem label="年度：" prop="year" >
                        <DatePicker class="query-form-el" type="year" placeholder="" v-model="form1.year1" :clearable="false"
                                    @on-change="()=>{if(form1.year1 instanceof Date){form1.year = form1.year1.getFullYear().toString()}}"
                        ></DatePicker>
                    </FormItem>
                </Col>
                <Col span="8">
<!--                    <Button @click="switchQuery(true)" class="ivu-btn-switch" type="text"  >展开∨</Button>-->
                    <Button @click="initSearchForm" class="ivu-btn-reset"  >重置</Button>
                    <Button type="primary" class="ivu-btn-query"   icon="md-search"  @click="query();loadLevelResultNum();">查询</Button>
                </Col>
            </Row>
            <Row class="query-form">
                <Col span="24" v-if="!isResult" style='height:40px;'>
                        <Button size="large" class="ivu-btn-add"  :loading="!enStdMap" icon="md-add"  @click="addInfo">新增</Button>
                        <Button type="primary" class="ivu-btn-add" :loading="buttonLoading" icon="md-cloud-download" @click="downloadFileTable">导出</Button>
                </Col>
                <Col span="24" style='height:40px;' v-else>
                    <Button size="large" class="ivu-btn-add" icon="md-checkbox-outline" :disabled="reportSelectAll.length<1" :loading="buttonLoading"
                            @click="submitReportSelect('1')">完成验收</Button>
                    <div class="right mt10 lh30" >
                        {{levelResultTotalNum}}家评定结果为：
                        <!--Ⅰ级19家，占比12.42%；Ⅱ级单位70家，占比45.75%；Ⅲ级单位48家，占比31.37%；不达标15家，占比9.8%-->
                        <template v-for="(item) in levelResultNumList">
                            <span v-for="(value, key) in item" class="ml10">{{key}}:{{value}}家<span v-if="levelResultTotalNum">,占比{{(100*value/levelResultTotalNum).toFixed(2)}}%</span></span>
                        </template>
                    </div>
                </Col>
            </Row>
        </Form>
        <Table ref='table' :height="tableHeight"  no-data-text="没有查询到相关数据!" @on-selection-change="reportSelect"
               @on-sort-change="sortChange"  border :columns="columns1"  :data="dataTable" >
        </Table>
        <Row style="margin-right:10px;">
            <Col span="24" >
                <Page style="float: right" :total="pagedata.total" :page-size="pagedata.pageSize" @on-change="pageChange" @on-page-size-change="pageSizeChange" :page-size-opts="pageSizeArray" show-total show-sizer show-elevator />
            </Col>
        </Row>
        <Modal :title=" add?(isResult?'新增现场验收评价':'新增环保标准化自评台账'):(isResult?'修改现场验收评价': '修改环保标准化自评台账')" :mask-closable="false" :transfer='false' v-model="selfCheckFormDialogShow" v-if="selfCheckFormDialogShow"  :styles="{height:'100%',width:'100%',minWidth:'1360px'}"   class-name='limit-height-dialog'>
          <self-check-form
		      ref='selfCheckForm'
              :data="dataToEdit"
              :mode="add?'add':'edit'"
              :enStdMap="enStdMap"
              @sending="function(data){pageStatus.sending=data}"
              @save-success="function(){handleCancel();query();}"
              @close-dialog="handleCancel"></self-check-form>
            <div slot="footer">
                <Button type="primary" class='ivu-btn-save' style="width: auto;" :loading="pageStatus.sending" @click="$refs.selfCheckForm.submit('selfCheckForm')">确定</Button>
                <Button type="primary" class='ivu-btn-cancel' @click="handleCancel">取消</Button>
            </div>
        </Modal>
        <Modal  :title="add?(isResult?'新增现场验收评价':'新增环保标准化自评台账'):(isResult?'现场验收评价': '修改环保标准化自评台账')" :mask-closable="false" :transfer='false' v-model="selfCheckResultDialogShow" v-if="selfCheckResultDialogShow"  :styles="{height:'100%',width:'100%',minWidth:'1360px'}"  class-name='limit-height-dialog'>
            <self-check-result
                    ref='selfCheckForm1'
                    :data="dataToEdit"
                    :mode="add?'add':'edit'"
                    :enStdMap="enStdMap"
                    :enStdCodingCodeIdMap="enStdCodingCodeIdMap"
                    @sending="function(data){pageStatus.sending=data}"
                    @save-success="function(){handleCancel();query();}"
                    @close-dialog="handleCancel"></self-check-result>
            <div slot="footer">
                <Button type="primary" class='ivu-btn-save' style="width: auto;" :loading="pageStatus.sending" @click="$refs.selfCheckForm1.submit('selfCheckForm')">确定</Button>
                <Button type="primary" class='ivu-btn-cancel' @click="handleCancel">关闭</Button>
            </div>
        </Modal>
        <Modal  :title="isResult?'现场验收评价':'环保标准化自评台账'" :transfer='false' v-model="selfCheckViewDialogShow" v-if="selfCheckViewDialogShow" :styles="{height:'100%',width:'100%',minWidth:'1360px'}"   class-name='limit-height-dialog'>
            <self-check-view :data="dataToView" :mode="isResult" @close-dialog="handleCancel" :enStdCodingCodeIdMap="enStdCodingCodeIdMap"></self-check-view>
            <div slot="footer">
                <Button class='ivu-btn-save' @click="handleCancel">关闭</Button>
            </div>
        </Modal>
    </Layout>
</template>

<script>
    import {Api} from '../../../../api'
    import SelfCheckForm from './compunents/Form'
    import SelfCheckResult from './compunents/Form1'
    import SelfCheckView from './compunents/View'
    var cascaderDom = () => import('@/components/cascader-dom.vue');
    import pageCommonFunction from '@/components/pageCommonFunction.js'
    import {cookie, sessionStorage} from '@/common/cacheUtils.js';

    export default {
        components:{
          SelfCheckForm, // 自查台账表单
          SelfCheckView, // 自查台账预览
          SelfCheckResult, // 评级结果
          cascaderDom,
        },
        computed:{
            // 是评级结果页面
            isResult(){
                return this.$route.name === 'selfEvaluationResult'
            },
            levelResultTotalNum(){
                var arr = this.levelResultNumList
                var total = 0
                arr.forEach(item=>{
                    for (var key in item){
                        total += parseInt(item[key])
                    }
                })
                return total
            },
            columns1() {
                const columns = [...this.columns];
                const columns1 = []
                columns.forEach(item => {
                    if (this.isResult) {
                            columns1.push(item)
                    } else {
                        if ( item.type !== 'selection' && item.title !=='现场审核专家'&& item.title !=='是否验收') {
                            columns1.push(item)
                        }
                    }
                })
                return columns1
            },
        },
        data(){
            return{
                switchFlag : false,
                form1: {
                    // companyId: JSON.parse(sessionStorage('userId').get('userId')).companyId,
                    // companyName: JSON.parse(sessionStorage('userId').get('userId')).companyName,
                },
                pageSizeArray: [10, 20, 50],
                pagedata: {
                    total: 0,
                    pageSize: 10,
                    currentPage: 1,
                },
                pageStatus: {
                    loading: false,
                    sending: false,
                    deleting: false
                },
                levelResultNumList:[], // 各等级企业数量统计数据
                dataTable:[],
                columns: [
                    { type: 'selection', width: 60, fixed: 'left', align: 'center',},
                    { title: '序号', width: 65, fixed: 'left', align: 'center', render: pageCommonFunction.indexColumnsRender.bind(this)},
                    { title: '是否验收', minWidth: 90, fixed: 'left',align: 'center',
                        render: (h,params)=>{return h('span',{style: {color: params.row.auditState==='1'?'red':''}},
                            params.row.auditState==='0'?'验收中':'验收完成')}},
                    { title: '名称', minWidth: 200, align: 'center', key:'name', },
                    { title: '二级集团', minWidth: 200, align: 'center', key:'belongOrgName', },
                    { title: '企业名称', minWidth: 200, align: 'center', key:'companyName', },
                    { title: '自评时间', width: 130, align: 'center', key:'selfLevelTime',sortable: "custom",
                        render: (h,params)=>{return h('span',this.renderViewDate(this.isResult?params.row.levelTime:params.row.selfLevelTime))},
                        renderHeader:(h,params)=>{return h('span',this.isResult?'现场评定时间':'自评时间')}},
                    // { title: '评定得分', width: 120, align: 'center', key:'evaluationScore',
                    //     render:(h,params)=>{return h('span',this.isResult?params.row.evaluationScore:params.row.evaluationScore1)}},
                    // { title: '涉及得分', width: 120, align: 'center', key:'involvedScore',
                    //     render:(h,params)=>{return h('span',this.isResult?params.row.involvedScore:params.row.involvedScore1)}},
                    { title: '综合评定得分', width: 130, align: 'center', key:'integretedScore',sortable: "custom",
                        render:(h,params)=>{return h('span',this.isResult?params.row.integretedScore:params.row.integretedScore1)}},
                    { title: '评定等级', width: 120, align: 'center', key:'level',
                        render:(h,params)=>{return h('span',(this.isResult?(params.row.level==''||params.row.level==undefined||params.row.level==null):params.row.level1=='')?'':this.enStdCodingCodeIdMap[this.isResult?params.row.level:params.row.level1].codingName)}},
                    { title: '现场审核专家', minWidth: 120, align: 'center', key:'expertNames', tooltip:true },
                    {
                        title: '操作',
                        key: 'action',
                        fixed: 'right',
                        width: 200,
                        align: 'center',
                        render: (h, params) => {
                            const enable = this.currentUser.loginId === this.Common.admin || this.currentUser.userId === params.row.createUserId||this.currentUser.userRole.find(obj => obj.roleId == '73b38b37dff64392ba0ee7dd579bf293') != undefined
                            || this.currentUser.userBeHandedOver.find(obj => obj == params.row.createUserId) != undefined;
                            if (this.isResult) {
                                return h('div', [
                                    h('A', {
                                        props: {type: 'primary', size: 'small'},
                                        style: {fontSize: '14px',},
                                        on: {
                                            click: () => {
                                                this.viewData(params);
                                            }
                                        }
                                    }, '详情'),
                                    h('Divider', { props: { type: 'vertical' } }, ''),
                                    h('A', {
                                        props: {type: 'primary', size: 'small'},
                                        style: {fontSize: '14px',
                                                    color: (params.row.auditState=='0'&&((params.row.experts&&params.row.experts.indexOf(this.currentUser.userId)>=0)|| this.currentUser.loginId === this.Common.admin || this.currentUser.userRole.find(obj => obj.roleId == '73b38b37dff64392ba0ee7dd579bf293') != undefined))?'':'#c5c8ce',
                                            pointerEvents:(params.row.auditState=='0'&&((params.row.experts&&params.row.experts.indexOf(this.currentUser.userId)>=0)|| this.currentUser.loginId === this.Common.admin || this.currentUser.userRole.find(obj => obj.roleId == '73b38b37dff64392ba0ee7dd579bf293') != undefined))?'':'none'},
                                        on: {
                                            click: () => {
                                                this.editData(params);
                                            }
                                        }
                                    }, '评价'),
                                    h('Divider', { props: { type: 'vertical' } }, ''),
                                    h('A', {
                                        props: {type: 'primary', size: 'small'},
                                        style: {fontSize: '14px',},
                                        on: {
                                            click: () => {
                                                this.downloadFile(params.row);
                                            }
                                        }
                                    }, '导出'),
                                    h('Divider', { props: { type: 'vertical' },
                                        style: {display:this.currentUser.loginId === this.Common.admin&&params.row.auditState=='1'?'':'none'} }, ''),
                                    h('A', {
                                        props: {type: 'primary', size: 'small'},
                                        style: {
                                            fontSize: '14px',color:'red',
                                            display:this.currentUser.loginId === this.Common.admin&&params.row.auditState=='1'?'':'none'
                                        },
                                        on: {
                                            click: () => {
                                                this.submitReportSelect('0',params.row.id);
                                            }
                                        }
                                    }, '验收重置'),
                                ]);
                            } else {
                                return h('div', [
                                    h('A', {
                                        props: {type: 'primary', size: 'small'},
                                        style: {fontSize: '14px',},
                                        on: {
                                            click: () => {
                                                this.viewData(params);
                                            }
                                        }
                                    }, '详情'),
                                    h('Divider', { props: { type: 'vertical' } }, ''),
                                    h('A', {
                                        props: {type: 'primary', size: 'small'},
                                        style: {fontSize: '14px', color: (this.isResult||(!this.isResult&&params.row.levelType!=2))&&enable?'':'#c5c8ce',pointerEvents:(this.isResult||(!this.isResult&&params.row.levelType!=2))&&enable?'':'none'},
                                        on: {
                                            click: () => {
                                                this.editData(params);
                                            }
                                        }
                                    }, this.isResult?'评价':'修改'),
                                    h('Divider', { props: { type: 'vertical' }, style: {display:this.isResult?'none':''} }, ''),
                                    h('A', {
                                        props: {type: 'primary', size: 'small'},
                                        style: {display:this.isResult?'none':'',fontSize: '14px', color: params.row.levelType!=2&&enable?'red':'#c5c8ce',pointerEvents:params.row.levelType!=2&&enable?'':'none'},
                                        on: {
                                            click: () => {
                                                this.deleteData(params);
                                            }
                                        }
                                    }, '删除'),
                                    h('Divider', { props: { type: 'vertical' } }, ''),
                                    h('A', {
                                        props: {type: 'primary', size: 'small'},
                                        style: {fontSize: '14px',},
                                        on: {
                                            click: () => {
                                                this.downloadFile(params.row);
                                            }
                                        }
                                    }, '导出'),
                                ]);
                            }
                        }
                    },
                ],
                enStdCodingCodeIdMap:{},// 评定等级ID列表
                // 添加、编辑弹出框相关参数
                add:false,
                selfCheckFormDialogShow:false,
                dataToEdit:{},
                enStdMap:null,// 评级等级显示列表
                // 查看页面相关数据
                selfCheckViewDialogShow:false,
                dataToView: null,
                // 填写结果弹出框
                selfCheckResultDialogShow:false,
                //
                carTypeList:[],
                gasTypeList:[],
                carPropertyList:[],
                tableHeight:10,
                currentUser: JSON.parse(sessionStorage('userId').get('userId')),
                buttonLoading: false,
                reportSelectAll:[]
            }
        },
        created() { },
        async mounted() {
            this.tableHeight = window.innerHeight - this.$refs.table.$el.offsetTop - 145;
            await this.initCoding()
            this.initSearchForm()
            this.loadLevelResultNum()
        },
        methods:{
            ...pageCommonFunction,
            // 基础数据
            async initCoding() {
                await this.$http.get(Api.queryCodeDetailBySortId + '/ENSTD-000001', {params: {}}).then((res) => {
                    var enStdList = res.data.data;
                    this.enStdCodingCodeIdMap = this.dictListToMap(enStdList)
                    this.enStdMap = this.dictListToMap(enStdList, 'codingShowId')
                });
            },
            // 加载评定等级数量
            loadLevelResultNum(){
                if (this.isResult){
                    var year = this.form1.year instanceof Date?this.form1.year.getFullYear():this.form1.year
                    this.$http.get(Api.getEnvSelfCheckStatistics, {params: {year:year==undefined?'':year}}).then((res) => {
                        this.levelResultNumList = res.data.data.data
                    });
                }
            },
            // search 表单方法
            initSearchForm(){
                this.form1 = {
                    year1: new Date(),
                    year:new Date().getFullYear().toString()
                }
                this.dataTable=[]
                if (this.isResult) {
                    // this.$set(this.form1,'year',new Date().getFullYear().toString())
                }
                this.$refs.carOrg.resetCurrentOrg();
                this.query()
            },

            reportSelect(select) {
                this.reportSelectAll = [];
                select.forEach(item => {
                    this.reportSelectAll.push(item.id)
                });
                console.log(this.reportSelectAll)
            },
            submitReportSelect(type,id) {
                let _this = this;
                if (type == 0) {
                    _this.reportSelectAll=[id]
                }
                if (_this.reportSelectAll.length !== 0) {
                    let config = {
                        title: '系统提示',
                        content: type == 0?'是否确定重置':'完成现场验收后不可修改，是否确定完成验收?',
                        okText: '确定',
                        cancelText: '取消',
                        onOk: function () {
                            _this.buttonLoading = true;
                            let data = {
                                userId: sessionStorage('userId').getObject('userId').userId,
                                list: _this.reportSelectAll,
                                type: type
                            }
                            this.$http.post(Api.submitEnvSelfCheckAll, data).then((res) => {
                                _this.buttonLoading = false;
                                if (res.data.status == '200') {
                                    _this.$Message.success("确认成功");
                                    _this.query();
                                } else {
                                    _this.$Message.warning(res.data.msg);
                                    _this.query();
                                }
                                _this.reportSelectAll = []
                            }).catch(e => {
                                _this.buttonLoading = false;
                                this.query();
                                this.$Message.error("失败")
                                _this.reportSelectAll = []
                            })
                        }
                    }
                    this.$Modal.confirm(config);
                } else {
                    _this.$Message.warning("请先勾选评价信息")
                }
            },
            setQueryOrgId(data) {
                this.form1.companyId = data[data.length - 1];
            },
            setQueryOrgName(data) {
                this.form1.companyName = data;
            },
            downloadFileTable() {
                this.buttonLoading = true
                let data ={
                    orgId:this.currentUser.companyId
                }
                data = Object.assign(data, JSON.parse(JSON.stringify(this.form1)));
                this.$http.get(Api.downLoadEnvSelfCheckList, {
                    params: data,
                    responseType: 'blob' //告诉服务器我们需要的响应格式
                }).then((res) => {
                    const aLink = document.createElement("a");
                    let blob = new Blob([res.data], {
                        type: res.bodyBlob.type //将会被放入到blob中的数组内容的MIME类型
                    });
                    aLink.href = URL.createObjectURL(blob)
                    aLink.download = "企业自评台账(" + this.formatDate(new Date(), "yyyy-MM-dd") + ").xlsx" //标题
                    aLink.click()
                    document.body.appendChild(aLink)
                    this.buttonLoading = false
                })
            },
            downloadFile(row) {
				this.downloadTable({
					formData: {},
					action: Api.downLoadEnvSelfCheck+'/'+row.id
				})
            },
            deleteData(params) {
              this.$Modal.confirm({
                title: '提示',
                content: '<p>确认删除此台账？</p>',
                onOk: () => {
                  this.$http.delete(Api.deleteEnvSelfCheck +'/'+ params.row.id, {params: {}}).then((res) => {
                    if (res.data.status === 200) {
                      this.$Message.success('删除成功');
                      this.query()
                    }else if (res.data.status === 201) {
                      this.$Message.error(res.data.msg);
                    }
                  }).catch(e => {
                    this.$Message.error('删除失败' + e);
                  })
                },
                onCancel: () => {
                }
              });
            },
            sortChange(data) {
                if (data.order === 'asc'||data.order ==='desc') {
                    let order = data.key
                    // let desc =  data.order ==='normal'?'asc': data.order
                    if (this.isResult) {
                        if (data.key === 'selfLevelTime') {
                            order = 'levelTime'
                        }
                    }else {
                       if (data.key === 'integretedScore') {
                            order = 'integretedScore1'
                        }
                    }
                    this.form1.order = order +' '+ data.order
                    this.query()
                }
            },
            addInfo(){
                if (this.isResult) {
                    this.selfCheckResultDialogShow =true
                }else {
                    this.selfCheckFormDialogShow = true;
                }
                this.add = true;
            },
            pageChange(pageNum) {
                this.pagedata.currentPage = pageNum;
                this.query();
            },
            pageSizeChange(pageSize) {
                this.pagedata.pageSize = pageSize;
                this.query();
            },
            handleCancel() {
                this.selfCheckFormDialogShow = false;
                this.selfCheckViewDialogShow = false;
                this.selfCheckResultDialogShow = false;
            },
            switchQuery(flag){
                this.switchFlag = flag;
                if(!this.switchFlag){
                     this.setTableHeight();
                }else{
                    this.tableHeight = window.innerHeight - 315;
                }
            },
            query() {
                let data = {
                    startPage: this.pagedata.currentPage,
                    size: this.pagedata.pageSize,
                    levelType: this.isResult?2:'',
                    orgId:this.currentUser.companyId,
                };
                data = Object.assign(data, JSON.parse(JSON.stringify(this.form1)));
                let url = Api.queryEnvSelfCheck;
                this.$http.get(url, {params: data}).then((res) => {
                    if (res.data.status === 201) {
                        this.$Message.error(res.data.msg);
                    }
                    this.dataTable = res.data.data.data;
                    this.pagedata.total = res.data.data.totalSize;
                    this.dataTable.forEach(item => {
                        if (item.auditState === '1') {
                            item['_disabled'] = true;
                        } else {
                            item['_disabled'] = true;
                            if (item.level&&((item.experts && item.experts.indexOf(this.currentUser.userId) >= 0) || this.currentUser.loginId === this.Common.admin || this.currentUser.userRole.find(obj => obj.roleId == '73b38b37dff64392ba0ee7dd579bf293') != undefined)) {
                                item['_disabled'] = false;
                            }
                        }
                    })
                }).catch(e => {
                    this.$Message.error("数据获取失败")
                })
            },
            viewData(data) {
                //查看页面
                this.$set(this,'dataToView', data.row);
                this.selfCheckViewDialogShow = true;
            },
            showDataResult(data){
                // 填写结果
                this.dataToView = data.row;
                this.selfCheckResultDialogShow = true;
            },
            editData(data) {
                //修改页面
                this.add = false;
                this.dataToEdit = data.row;
                if (this.isResult) {
                    this.selfCheckResultDialogShow =true
                }else {
                    this.selfCheckFormDialogShow = true;
                }
            },
            formatDate(date, fmt) {
                if (/(y+)/.test(fmt)) {
                    fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length));
                }
                let o = {
                    'M+': date.getMonth() + 1,
                    'd+': date.getDate(),
                    'h+': date.getHours(),
                    'm+': date.getMinutes(),
                    's+': date.getSeconds()
                };
                for (let k in o) {
                    if (new RegExp(`(${k})`).test(fmt)) {
                        let str = o[k] + '';
                        fmt = fmt.replace(RegExp.$1, RegExp.$1.length === 1 ? str : this.padLeftZero(str));
                    }
                }
                return fmt;
            },
            padLeftZero(str) {
                return ('00' + str).substr(str.length);
            },
        },
        watch:{
            '$route.name':function(){
                this.initSearchForm()
                this.loadLevelResultNum()
            }
        },

    }
</script>

<style lang='css' scoped>
</style>
